﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Islamic_influence_in_Venetian_cuture.LangResources;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Utils.WP7.Bing;
using Utils.WP7.Bing.BingGeo;
using System.Windows.Data;
using Utils.WP7.Bing.BingRoute;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;

namespace Islamic_influence_in_Venetian_cuture.View
{
    //public enum Influence
    //{
    //    Glass = 0,
    //    Textile = 1,
    //    Carpet = 2,
    //    Architecture = 3,
    //    Painting = 4,
    //    Cook = 5
    //}


    public partial class InfluenceContent : PhoneApplicationPage
    {
        Lang lang;

        public InfluenceContent()
        {
            lang = new Lang();
            DataContext = lang;
            //DataContext = "/Resources/Panorama/1.png"; //(from i in Enumerable.Range(0, 8) select "/Resources/Panorama/" + i + ".png").ToArray();
                //DataContext = lang;
            InitializeComponent();

            //Image myImage = new Image();
            //myImage.Source = new BitmapImage(new Uri("/Resources/Panorama/1.png", UriKind.RelativeOrAbsolute));

            Page.Background = new ImageBrush() { Stretch = Stretch.UniformToFill, ImageSource = getBackground() };
            //LayoutRoot.Children.Add(myImage);

            //new ImageBrush() { ImageSource = "ciao" };


            //foreach (var part in Page.Items)
            //{
            //    (part as PanoramaItem).DataContext = lang;
            //}
            lang.PropertyChanged += new PropertyChangedEventHandler(lang_PropertyChanged);
            SetTitle(lang);
            ImageList.DataContext = InfluenceImageAndCaption.FromResx(lang);
            Description.DataContext = new InfluenceDescriptionData(lang);
            // Initialize the viewmodel.
            var address = GetAddress();
            RouteViewModel vm = null;
            if (address != null)
                vm = new RouteViewModel(GetAddress(), TravelMode.Walking);
            //vm.RouteResolved += (s, e) => { Page. = 2; };

            var description_binding = new Binding("GetDirections");
            description_binding.Source = lang;
            DirectionsControl.SetBinding(PanoramaItem.HeaderProperty, description_binding);

            var map_binding = new Binding("MapTitle");
            map_binding.Source = lang;
            MapController.SetBinding(PanoramaItem.HeaderProperty, map_binding);

            // Set datacontext.
            DirectionsControl.DataContext = vm;
            MapController.DataContext = vm;
            

            //var button = new ApplicationBarIconButton();
            //button.IconUri = new Uri("/Resources/IntroVideo.jpg", UriKind.Relative);
            //button.Text = "ciao " + (new Random()).Next(10);

            //appBar.Buttons.Add(button);

            //IconUri="/Images/appbar_button1.png" Text="Walk" Click="ApplicationBarIconButton_Click_1"/>
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Page.Background = new ImageBrush() { Stretch = Stretch.UniformToFill, ImageSource = getBackground() };
            base.OnNavigatedTo(e);
        }

        private Address GetAddress()
        {
            var address = new Address();
            var parts = (typeof(GlobalRes).GetProperty("Coordinate" + InfluenceKind.KindIndex).GetGetMethod().Invoke(null, null) as string).Split(new char[] { ';' });
            if (parts.Where(s => s.Trim().Length > 0).Count() < 1)
                return null;
            address.AddressLine = parts[0];
            address.PostalTown = parts[1];
            address.PostalCode = parts[2];
            address.CountryRegion = parts[3];

            return address;
        }

        void lang_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            SetTitle(lang);
        }

        private void SetTitle(Lang lang)
        {
            try
            {
                Page.Title = typeof(Lang).GetProperties().Where(p => p.Name == "ArtContent" + InfluenceKind.KindIndex).First().GetGetMethod().Invoke(lang, null) as string;
            }
            catch (Exception)
            {
            }
        }

        #region AppBar
        private void Arabic_bar_Click(object sender, EventArgs e)
        {
            LangResources.Lang.CurrentCulture = LangResources.Cultures.Arabic;
        }

        private void English_bar_Click(object sender, EventArgs e)
        {
            LangResources.Lang.CurrentCulture = LangResources.Cultures.English;
        }

        private void Farsi_bar_Click(object sender, EventArgs e)
        {
            LangResources.Lang.CurrentCulture = LangResources.Cultures.Persian;
        }

        private void Italian_bar_Click(object sender, EventArgs e)
        {
            LangResources.Lang.CurrentCulture = LangResources.Cultures.Italiano;
        }
        #endregion

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            var elem = (MapController.DataContext as RouteViewModel);
            if (elem != null && !RouteViewModel.IsBusy)
            {
                MessageBox.Show("working");
                try
                {
                    elem.ResolveRouteFromCurrent();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            var button = sender as ApplicationBarIconButton;
            var elem = (MapController.DataContext as RouteViewModel);
            if (elem == null)
                return;
            switch (elem.TravelMode)
            {
                case TravelMode.Walking:
                    button.Text = "Lang.Walk";
                    button.IconUri = new Uri("/Resources/BarIcons/Walk.png", UriKind.Relative);
                    elem.TravelMode = TravelMode.Driving;
                    ApplicationBarIconButton_Click(null, null);
                    break;
                case TravelMode.Driving:
                    button.Text = "Walk.Drive";
                    button.IconUri = new Uri("/Resources/BarIcons/Drive.png", UriKind.Relative);
                    elem.TravelMode = TravelMode.Walking;
                    ApplicationBarIconButton_Click(null, null);
                    break;
                default:
                    break;
            }
        }

        private static BitmapImage getBackground()
        {
            var idx = (new Random()).Next(9);

            return new BitmapImage(new Uri("/Resources/Panorama/" + idx + ".png", UriKind.RelativeOrAbsolute));
        }

        private void Description_GotFocus(object sender, RoutedEventArgs e)
        {
#warning focus!!!!!
            Page.Focus();
        }
    }


    public class InfluenceKind
    {
        public static string KindIndex { get; set; }
    }


    public class InfluenceImageAndCaption : INotifyPropertyChanged
    {
        private Lang _lang;
        private int _index;

        private string _caption;

        public string Caption
        {
            get { return _caption; }
            private set { _caption = value; }
        }

        private string _source;

        public string Source
        {
            get { return _source; }
            private set { _source = value; }
        }

        public Cultures Culture { get { return Lang.CurrentCulture; } }

        public InfluenceImageAndCaption(Lang lang ,int index)
        {
            _index = index;
            _lang = lang;
            lang.PropertyChanged += new PropertyChangedEventHandler(lang_PropertyChanged);
            
            _source = "/Resources/" + InfluenceKind.KindIndex + "/" + index + ".jpg";

            var captions =
                (typeof(Lang).GetProperties().Where(p => p.Name == "ImageDescription" + InfluenceKind.KindIndex).First().GetGetMethod().Invoke(lang, null) as string).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            _caption = captions[index];
        }

        void lang_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var captions =
                (typeof(Lang).GetProperties().Where(p => p.Name == "ImageDescription" + InfluenceKind.KindIndex).First().GetGetMethod().Invoke(_lang, null) as string).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            _caption = captions[_index];
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(""));
        }

        public static ObservableCollection<InfluenceImageAndCaption> FromResx(Lang lang)
        {
            var captions =
                (typeof(Lang).GetProperties().Where(p => p.Name == "ImageDescription" + InfluenceKind.KindIndex).First().GetGetMethod().Invoke(lang, null) as string).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            var list = new ObservableCollection<InfluenceImageAndCaption>();

            for (int i = 0; i < captions.Length; i++)
            {
                list.Add(new InfluenceImageAndCaption(lang, i));
            }

            return list;
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class InfluenceDescriptionData : INotifyPropertyChanged
    {
        private Lang _lang;
        public Cultures Culture { get { return Lang.CurrentCulture; } }

        private string _description;

        public string Description
        {
            get { return typeof(Lang).GetProperties().First(p => p.Name == "ContentArt" + InfluenceKind.KindIndex).GetGetMethod().Invoke(_lang, null) as string; }
            private set { _description = value; }
        }
        

        public InfluenceDescriptionData(Lang lang)
        {
            _lang = lang;
            lang.PropertyChanged += new PropertyChangedEventHandler(lang_PropertyChanged);
        }

        private void SetDescription()
        {
            _description = typeof(Lang).GetProperties().First(p => p.Name == "ContentArt" + InfluenceKind.KindIndex).GetGetMethod().Invoke(_lang, null) as string;
        }

        void lang_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(""));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class TravelModeConverter : IValueConverter
    {
        private static readonly string Walk = "Walk there";
        private static readonly string Drive = "Drive there";

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch ((TravelMode)value)
            {
                case TravelMode.Driving:
                    return Drive;
                case TravelMode.Walking:
                    return Walk;
                default:
                    return Walk;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


}